package com.unlcn.ils.sales.backend.service;

import cn.huiyunche.commons.exception.BusinessException;
import com.google.common.collect.Lists;
import com.unlcn.ils.sales.backend.bo.BonusBalanceBO;
import com.unlcn.ils.sales.backend.bo.UserViewBO;
import com.unlcn.ils.sales.base.mapper.SaleBonusBalanceMapper;
import com.unlcn.ils.sales.base.model.SaleBonusBalance;
import com.unlcn.ils.sales.base.model.SaleBonusBalanceExample;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * Created by houjianhui on 2017/6/5.
 */

@Service
public class BonusBalanceServiceImpl implements BonusBalanceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BonusBalanceServiceImpl.class);

    @Autowired
    private SaleBonusBalanceMapper bonusBalanceMapper;
    @Autowired
    private UserService userService;

    @Override
    public BigDecimal getUserBalanceByUserId() throws Exception {
        UserViewBO user = userService.getCurrentUser();
        // 通过用户ID查询余额信息
        SaleBonusBalance bonusBalance = getBonusBalanceByUserId(user.getId());
        if (!Objects.equals(bonusBalance, null) && !Objects.equals(bonusBalance, "")) {
            return bonusBalance.getBalance();
        }
        return new BigDecimal(0);
    }

    private SaleBonusBalance getBonusBalanceByUserId(Integer userId) {
        List<SaleBonusBalance> balances = Lists.newArrayList();
        SaleBonusBalanceExample example = new SaleBonusBalanceExample();
        example.createCriteria().andUserIdEqualTo(userId).andDeleteMarkEqualTo(true);
        try {
            balances = bonusBalanceMapper.selectByExample(example);
        } catch (Exception e) {
            LOGGER.error("BonusBalanceServiceImpl.getuserBalanceByUserId error: {}", e);
            throw new BusinessException("根据用户ID查询用户余额信息异常");
        }
        if (CollectionUtils.isNotEmpty(balances)) {
            return balances.get(0);
        }
        return null;
    }

    @Override
    public Integer updateUserBalance(BigDecimal balance, BigDecimal withdrawalBalance) throws Exception {
        LOGGER.info("BonusBalanceServiceImpl.updateUserBalance params balance: {}, withdrawalBalance: {}", balance, withdrawalBalance);
        if (Objects.equals(balance, null) || Objects.equals(balance, "")) {
            LOGGER.info("BonusBalanceServiceImpl.updateUserBalance params balance must not be null");
        } else if (Objects.equals(withdrawalBalance, null) || Objects.equals(withdrawalBalance, "")) {
            LOGGER.info("BonusBalanceServiceImpl.updateUserBalance params withdrawalBalance must not be null");
        }
        UserViewBO user = userService.getCurrentUser();
        // 通过用户ID查询余额信息
        SaleBonusBalance bonusBalance = getBonusBalanceByUserId(user.getId());
        if (Objects.equals(bonusBalance, null) || Objects.equals(bonusBalance, "")) {
            LOGGER.info("BonusBalanceServiceImpl.updateUserBalance The current user BonusBalance does not exist");
            throw new BusinessException("当前用户余额信息不存在");
        }
        // 设置余额
        bonusBalance.setBalance(balance);
        // 设置可提现金额
        bonusBalance.setWithdrawalBalance(withdrawalBalance);

        try {
            // 更新钱包余额
           return bonusBalanceMapper.updateByPrimaryKeySelective(bonusBalance);
        } catch (Exception e) {
            LOGGER.error("BonusBalanceServiceImpl.updateUserBalance error: {}", e);
            throw new BusinessException("更新用户钱包余额异常");
        }
    }

    @Override
    public Integer save(BonusBalanceBO bo) throws Exception {
        LOGGER.info("BonusBalanceServiceImpl.save param BonusBalanceBO: {}", bo);

        if (Objects.equals(bo, null) || Objects.equals(bo, "")){
            LOGGER.info("BonusBalanceServiceImpl.save param BonusBalanceBO must not be null");
            throw new IllegalArgumentException("钱包余额表单不能为空");
        }

        // 校验用户钱包数据是否存在
        SaleBonusBalance balance = getBonusBalanceByUserId(bo.getUserId());
        if (!Objects.equals(balance, null) && !Objects.equals(balance, "")) {
            LOGGER.info("BonusBalanceServiceImpl.save param BonusBalanceBO existing");
            throw new BusinessException("当前用户已存在钱包余额信息");
        }

        // 拷贝数据
        SaleBonusBalance bonusBalance = new SaleBonusBalance();
        BeanUtils.copyProperties(bo, bonusBalance);
        try {
            // 保存钱包余额
            return bonusBalanceMapper.insertSelective(bonusBalance);
        } catch (Exception e){
            LOGGER.error("BonusBalanceServiceImpl.save error: {}", e);
            throw new BusinessException("保存钱包余额异常");
        }
    }
}
